package uutalk.netcloud.talk.app.ui.fragment;


import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.apkfuns.logutils.LogUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.app.Constants;
import uutalk.netcloud.talk.app.ui.Activity.ActShareActivity;
import uutalk.netcloud.talk.app.ui.ContentActivity;
import uutalk.netcloud.talk.app.ui.MainActivity;
import uutalk.netcloud.talk.app.ui.adapter.GroupMemberAdapter;
import uutalk.netcloud.talk.base.android.BaseFragment;
import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.VibratorUtil;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.TalkManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.base.widget.CenterWindowTips;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.DBEntityManager;
import uutalk.netcloud.talk.model.bean.GroupInfoBean;
import uutalk.netcloud.talk.model.bean.GroupMember;
import uutalk.netcloud.talk.model.bean.GroupMemberWrap;
import uutalk.netcloud.talk.model.bean.QuitGroupRsp;
import uutalk.netcloud.talk.model.bean.SimpleEvent;
import uutalk.netcloud.talk.model.bean.SimpleEventType;

/**
 * A simple {@link Fragment} subclass.
 */
public class GroupInfoFragment extends BaseFragment {

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;

    @BindView(R.id.tvGroupName)
    TextView tvGroupName;

    @BindView(R.id.tvBut)
    TextView tvBut;

    @BindView(R.id.btnStartTalk)
    Button btnStartTalk;

    @BindView(R.id.btnDeleteGroup)
    Button btnDeleteGroup;

    @BindView(R.id.btn_out_group)
    Button btn_out_group;

    @BindView(R.id.ll_group)
    LinearLayout ll_group;

    @BindView(R.id.rl_group)
    RelativeLayout rl_group;

    @BindView(R.id.llHistory)
    LinearLayout llHistory;

    @BindView(R.id.start_talk)
    ImageView startTalkView;


    private String groupID;
    private String groupName;
    GroupInfoBean groupInfoBean;
    boolean isSpeak;



    public static GroupInfoFragment newInstance(String groupID, String groupName) {
        GroupInfoFragment fragment = new GroupInfoFragment();
        fragment.groupID = groupID;
        fragment.groupName = groupName;
        return fragment;
    }

    @Override
    public boolean supportActionbar() {
        return true;
    }

    @Override
    public boolean isAutoBindEvent() {
        return true;
    }

    @Override
    protected int setLayoutResId() {
        return R.layout.fragment_group_member;
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void init() {
        getTitleTV().setText(LanguageUtil.getStringById(R.string.str_group_info)+groupName);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 4));
        if(TextUtils.isEmpty(groupID)){
            finish();
            return;
        }
        requestGroupMember(groupID);
        requestGroupInfo();
        if(groupID.equals(TalkManager.getInstance().getCurrentChannel())){
            btnStartTalk.setVisibility(View.VISIBLE);
            ll_group.setVisibility(View.GONE);
        }
        btnStartTalk.setEnabled(false);
        btnDeleteGroup.setEnabled(false);
        //加入群
        TalkManager.getInstance().joinChannel(groupID,UserManager.getInstance().getUserInfo().getUser_id());
        setTalkBtnTouchEvent();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMessageEvent(MqttMessageEvent event) {
        if (CMDConstant.GET_GROUP_INFO_RESP_CMD.equals(event.getMessage().getCmd())) {
            progressHudUtil.dismissProgressHud();
            groupInfoBean = JSON.parseObject(event.getMessage().toString(), GroupInfoBean.class);
            if (groupInfoBean.isOk()) {
                initActInfoLayout();
            } else {
                ToastUtil.makeToast(groupInfoBean.getError_msg());
            }
        } else if (CMDConstant.LEAVE_GROUP_RESP_CMD.equals(event.getMessage().getCmd())) {
            //离开群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                ToastUtil.makeToast("已离开群聊.");
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.DISMISS_GROUP_RESP_CMD.equals(event.getMessage().getCmd())){
            //退出群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                ToastUtil.makeToast("已解散群聊.");
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.QUIT_GROUP_RESP_CMD.equals(event.getMessage().getCmd())){
            //退出群
            progressHudUtil.dismissProgressHud();
            QuitGroupRsp group = JSON.parseObject(event.getMessage().toString(), QuitGroupRsp.class);
            if (group.isOk()) {
                ToastUtil.makeToast("已退出群聊.");
                finish();
            } else {
                ToastUtil.makeToast(group.getError_msg());
            }
        } else if(CMDConstant.GET_GROUP_MEMBER_RESP_CMD.equals(event.getMessage().getCmd())){
            progressHudUtil.dismissProgressHud();
            //请求服务器
            GroupMemberWrap groupMemberWrap = JSON.parseObject(event.getMessage().toString(), GroupMemberWrap.class);
            if (groupMemberWrap.isOk()) {
                if (groupMemberWrap.getMember_list() != null && groupMemberWrap.getMember_list().size() > 0) {
                    List<GroupMember> groupMembers = groupMemberWrap.getMember_list();
                    int size = groupMembers.size();
                    GroupMember groupMember;
                    //保存服务器返回的所有群组成员保存到数据库中
                    for (int i = 0; i < size; i++) {
                        groupMember = groupMembers.get(i);
                        groupMember.setGroup_id(groupID);
                        DBEntityManager.saveGroupMember(groupMember);
                    }
                    Collections.sort(groupMembers);
                    GroupMemberAdapter groupMemberAdapter = new GroupMemberAdapter(mActivity, groupMembers);
                    recyclerView.setAdapter(groupMemberAdapter);
                }
            } else {

            }

        }
    }

    @OnClick({R.id.tvQrCode, R.id.btnDeleteGroup, R.id.btn_out_group, R.id.llHistory})
    public void OnViewClick(View view){
        switch (view.getId()){
            case R.id.tvQrCode:{
                Intent intentShare = new Intent(mActivity, ActShareActivity.class);
                intentShare.putExtra("group_name", groupInfoBean.getGroup_name());
                intentShare.putExtra("group_id", groupInfoBean.getGroup_id());
                startActivity(intentShare);
            } break;
            case R.id.btnDeleteGroup:{
                CenterWindowTips centerWindowTips = new CenterWindowTips(mActivity);
                centerWindowTips.setTitleStr(LanguageUtil.getStringById(R.string.str_tip));
                centerWindowTips.setContentStr(LanguageUtil.getStringById(R.string.str_leave_group_tip));
                centerWindowTips.setType(CenterWindowTips.TYPE_DOUBLE);
                centerWindowTips.setClickListener(new CenterWindowTips.OnClickListener() {
                    @Override
                    public void onSureClick() {
                        leaveGroup(groupInfoBean.getGroup_id());
                    }

                    @Override
                    public void onCancelClick() {

                    }
                });
                centerWindowTips.show();
            } break;
            case R.id.btn_out_group:{
                if(btn_out_group.getText().toString().trim().equals("退出群聊")){
                    CenterWindowTips centerWindowTips = new CenterWindowTips(mActivity);
                    centerWindowTips.setTitleStr(LanguageUtil.getStringById(R.string.str_tip));
                    centerWindowTips.setContentStr(LanguageUtil.getStringById(R.string.str_delete_group_tip));
                    centerWindowTips.setType(CenterWindowTips.TYPE_DOUBLE);
                    centerWindowTips.setClickListener(new CenterWindowTips.OnClickListener() {
                        @Override
                        public void onSureClick() {
                            quitGroup(groupInfoBean.getGroup_id());
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    });
                    centerWindowTips.show();
                }else {
                    CenterWindowTips centerWindowTips = new CenterWindowTips(mActivity);
                    centerWindowTips.setTitleStr(LanguageUtil.getStringById(R.string.str_tip));
                    centerWindowTips.setContentStr("是否解散此群?");
                    centerWindowTips.setType(CenterWindowTips.TYPE_DOUBLE);
                    centerWindowTips.setClickListener(new CenterWindowTips.OnClickListener() {
                        @Override
                        public void onSureClick() {
                            dismissGroup(groupInfoBean.getGroup_id());
                        }

                        @Override
                        public void onCancelClick() {

                        }
                    });
                    centerWindowTips.show();
                }

            } break;

            case R.id.llHistory:{
                Intent intent = new Intent(mActivity, ContentActivity.class);
                intent.putExtra(Constants.KEY_FRAGMENT, Constants.GROUP_HISTORY_FRAGMENT);
                intent.putExtra(Constants.KEY_UID, groupID);
                startActivity(intent);
            } break;
            default:
                break;
        }
    }

    @Override
    public void gc() {
        super.gc();
        TalkManager.getInstance().leaveChannel();
    }

    void initActInfoLayout() {

        if(isGroupOwner()){
            btn_out_group.setText("解散群聊");
        }else {
            btn_out_group.setText("退出群聊");
        }
        if(TextUtils.isEmpty(groupInfoBean.getGroup_info())){
            tvBut.setText(LanguageUtil.getStringById(R.string.str_no_group_bulletin));
        } else {
            tvBut.setText(groupInfoBean.getGroup_info());
        }

        tvGroupName.setText(groupInfoBean.getGroup_name());
        tvGroupName.setGravity(Gravity.CENTER_VERTICAL);

        btnStartTalk.setEnabled(true);
        btnDeleteGroup.setEnabled(true);
        rl_group.setVisibility(View.VISIBLE);

    }

    //离开群
    public boolean leaveGroup(String groupId) {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createQuitActivityBean(CMDConstant.LEAVE_GROUP_CMD, groupId));
            MQTTManager.getInstance().publish(publication);
            return true;
        } else {
            ToastUtil.makeToast("请求失败,请重试");
            return false;
        }

    }

    //解散群
    public boolean dismissGroup(String groupId) {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createQuitActivityBean(CMDConstant.DISMISS_GROUP_CMD, groupId));
            MQTTManager.getInstance().publish(publication);
            return true;
        } else {
            ToastUtil.makeToast("请求失败,请重试");
            return false;
        }

    }

    //退出群
    public boolean quitGroup(String groupId) {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createQuitActivityBean(CMDConstant.QUIT_GROUP_CMD, groupId));
            MQTTManager.getInstance().publish(publication);
            return true;
        } else {
            ToastUtil.makeToast("请求失败,请重试");
            return false;
        }
    }

    /**
     * 是否按住了说话按钮
     *
     * @param isPress
     */
    private void onTalkBtnPress(boolean isPress, boolean isVibrate) {
        if (isPress) {
            if (isSpeak) {
                return;
            }
            isSpeak = true;
            if(isVibrate){
                VibratorUtil.Vibrate(mActivity, 100);
                startTalkView.setImageResource(R.drawable.talk_anim);
                AnimationDrawable drawable = (AnimationDrawable) startTalkView.getDrawable();
                drawable.start();
            }

            TalkManager.getInstance().openMic(true);
            EventMamager.getInstance().postStringEvent(SimpleEventType.SOUND_DATA_ARRIVED, UserManager.getInstance().getUserInfo().getUser_id());
            LogUtils.e("按下说话");
        } else {
            if (!isSpeak) {
                return;
            }
            LogUtils.e("停止说话");
            isSpeak = false;
            TalkManager.getInstance().openMic(false);
            startTalkView.setImageResource(R.drawable.f1);
        }
    }


    /**
     * 设置说话按点触摸事件
     */
    public void setTalkBtnTouchEvent() {

        startTalkView.setOnTouchListener((View v, MotionEvent event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                onTalkBtnPress(true, true);
            } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                onTalkBtnPress(false, true);
            }
            return true;
        });
    }

    /**
     * 请求群组信息
     */
    public void requestGroupInfo() {
        if (MQTTManager.getInstance().isConnected()) {
            progressHudUtil.showProgressHud(false);
            Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetGroupInfoBean(groupID));
            MQTTManager.getInstance().publish(publication);
            Log.e(TAG, "requestGroupInfo groupID>>"+groupID);
        } else {
            ToastUtil.makeToast(R.string.request_error);
        }
    }

    /**
     * 获取群组成员
     *
     * @param groupId
     */
    public void requestGroupMember(String groupId) {
        if(!TextUtils.isEmpty(groupId)){
            if (MQTTManager.getInstance().isConnected()) {
                progressHudUtil.showProgressHud();
                Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetGroupMemberBean(groupId));
                MQTTManager.getInstance().publish(publication);
            } else {
                ToastUtil.makeToast(R.string.request_error);
            }
        }
    }

    /**
     * 群成员响应
     * @param event
     */
    private void onGroupMemberRespCMD(MqttMessageEvent event) {
        GroupMemberWrap groupMemberWrap = JSON.parseObject(event.getMessage().toString(), GroupMemberWrap.class);
        if (groupMemberWrap.isOk()) {
            if (groupMemberWrap.getMember_list() != null && groupMemberWrap.getMember_list().size() > 0) {
                List<GroupMember> groupMembers = groupMemberWrap.getMember_list();
                int size = groupMembers.size();
                GroupMember groupMember;
                //保存服务器返回的所有群组成员保存到数据库中
                for (int i = 0; i < size; i++) {
                    groupMember = groupMembers.get(i);
                    groupMember.setGroup_id(groupID);
                    DBEntityManager.saveGroupMember(groupMember);
                }
            }
        } else {

        }
    }

    /**
     * 判断是否是群主创建人
     * @return
     */
    private boolean isGroupOwner(){
        Log.e("GroupInfoFragment", "isGroupOwner>>"+groupInfoBean.getOwner_id() + "userid>>" + UserManager.getInstance().getUserInfo().getUser_id());
        if(groupInfoBean != null){
            if(groupInfoBean.getOwner_id().equals(UserManager.getInstance().getUserInfo().getUser_id())){
                return true;
            }
        }
        return false;
    }
}
